package dapps.web.document;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletContext;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.dispatcher.StreamResult;
import org.apache.struts2.util.ServletContextAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.web.struts2.CRUDActionSupport;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import dapps.entity.document.Attachment;
import dapps.service.document.AttachmentManager;

@SuppressWarnings("serial")
@Results( { @Result(name = CRUDActionSupport.SUCCESS, params={"inputName","inputStream","contentDisposition","filename=${fileName}"},  type = "stream")})
public class GetattachmentAction extends ActionSupport implements ServletContextAware{
	@Autowired
	private AttachmentManager attachmentManager;
	private Long attachmentid; 
	private ServletContext servletContext;
	private String fileName;


	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	public InputStream getInputStream() throws Exception {
    	Attachment am = attachmentManager.get(attachmentid);
        String imageDirectory = servletContext.getRealPath(am.getPath());
        fileName = am.getFileName();
        // retrieve default image if no file was found
        File file = new File(imageDirectory, fileName);
        if (file.exists()) {
        	com.opensymphony.xwork2.Result result = ActionContext.getContext().getActionInvocation().getResult();
            if (result != null && result instanceof StreamResult) {
                StreamResult streamResult = (StreamResult) result;
                streamResult.setContentType(am.getContentType());
            }
            
            try {
                return new FileInputStream(file);
            } catch (IOException ex) {
            }
        } 
        return null;
	}

	public Long getAttachmentid() {
		return attachmentid;
	}

	public void setAttachmentid(Long attachmentid) {
		this.attachmentid = attachmentid;
	}

	public String getFileName() throws UnsupportedEncodingException {
		fileName=new String(fileName.getBytes(),"ISO-8859-1"); 
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}


}
